package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.TourDAO;
import com.iddaa.core.domain.Tour;
import com.iddaa.core.service.SolrService;
import com.iddaa.core.service.TourService;
import com.iddaa.core.util.Constants;

@Service("tourService")
@Memcached(prefix = "Tour", expiration = Constants.Cache.TOUR_EXPIRETIME)
public class TourServiceImpl implements TourService {

	@Autowired
	private TourDAO tourDAO;

	@Autowired
	private SolrService solrService;

	@Override
	public void deleteTour(Long id) {
		tourDAO.delete(findById(id));
		solrService.updateSolr(id,"Tour");
		deleteCache(id);
	}

	@Override
	@MemcachedRead
	public Tour findById(Long id) {
		return tourDAO.getById(id);
	}

	@Override
	public Collection<Tour> loadAll() {
		return tourDAO.loadAll();
	}

	@Override
	public void saveTour(Tour tour) {
		tourDAO.saveOrUpdate(tour);
		solrService.updateSolr(tour.getId(), tour.getHome().getShortName() + " - " + tour.getAway().getShortName(), "Tour");
		evictCache(tour);
	}

	@Async
	public void evictCache(Tour tour) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("Tour:" + tour.getId(), Constants.Cache.TOUR_EXPIRETIME, tour);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("Tour:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
